﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;

namespace Kit3D.Xml
{
    public class XmlDocument : XmlNode
    {
        public XmlElement DocumentElement { get; set; }

        public void Load(XmlReader xmlReader)
        {
            xmlReader.MoveToContent();
            if (xmlReader.NodeType == XmlNodeType.Element)
            {
                DocumentElement = GetCurrentElement(xmlReader);
            }
        }

        private static XmlElement GetCurrentElement(XmlReader reader)
        {
            if (reader.NodeType != XmlNodeType.Element)
                throw new ArgumentException("must be at NodeType Element", "reader");

            var element = new XmlElement();
            element.Name = reader.Name;

            while (reader.MoveToNextAttribute())
                element.Attributes.Add(reader.Name, reader.Value);
            if (element.Attributes.Count != 0)
                reader.MoveToElement();

            AssignAllChildElements(reader, element);

            return element;
        }

        private static void AssignAllChildElements(XmlReader reader, XmlElement parent)
        {
            if (reader.IsEmptyElement)
                return;

            var parentDepth = reader.Depth;

            var content = new StringBuilder();

            while (reader.Read() && !reader.EOF && reader.Depth > parentDepth)
            {
                if (reader.NodeType == XmlNodeType.EndElement)
                    return;

                if (reader.NodeType == XmlNodeType.Element)
                {
                    parent.Children.Add(GetCurrentElement(reader));
                    continue;
                }

                content.Append(reader.Value);
            }

            parent.Value = content.ToString();
        }
    }
}
